import type { IUserData } from '../../../user_center/tab/personalization/custom_css/theme/others/greasy_fork/module/script_processor/types'
import type { GreasyForkUserType } from '../../../user_center/tab/personalization/custom_css/theme/others/greasy_fork/module/storage_process/types'
import {
  AppStyleCollections,
  BodyClasses,
  BUILD_CONFIG,
  PROJECT_PREFIX,
} from '../../../types/constants'
import { StylesService } from '../../../types/constants/styles'
import { GreasyFork } from '../../../user_center/tab/personalization/custom_css/theme/others/greasy_fork/page/lib'
import { getUserBadgeStyles, USER_TAG_LABELS } from '../../../user_center/tab/personalization/custom_css/theme/others/greasy_fork/page/lib/types'
import { ThemeVarService } from '../../abstract/style/theme_var/service'
import { ContributorHandler } from '../../contributor_handler'
import { ContributorRole } from '../../contributor_handler/interfaces'
import { IconService } from '../../icons'
import { ICON_IDS } from '../../icons/types/constants'

export class PageUserHandler {
  private static instance: PageUserHandler
  private readonly iconService: IconService = IconService.getInstance()
  private readonly contributorHandler: ContributorHandler = ContributorHandler.getInstance()
  protected readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly stylesService: StylesService = StylesService.getInstance()
  private readonly greasyFork: GreasyFork = GreasyFork.getInstance()
  readonly scriptStarClass: string = 'script-star'
  private readonly avatarContainerClass: string = AppStyleCollections.Body.AVATAR_CONTAINER

  /**
   * 获取单例实例
   */
  public static getInstance(): PageUserHandler {
    if (!PageUserHandler.instance) {
      PageUserHandler.instance = new PageUserHandler()
    }
    return PageUserHandler.instance
  }

  /**
   * 添加用户头像
   */
  addAvatar($element: JQuery, data: IUserData): void {
    const authorId = this.greasyFork!.extractUserIdFromUrl(data.authorUrl)
    const isCreator = this.isCreator(authorId)
    const isCurrentUser = this.greasyFork!.getCurrentUserId() === authorId

    if ($element.find(`.${this.avatarContainerClass}`).length > 0)
      return

    $element.prepend(`
      <div class="${this.avatarContainerClass}">
      <img 
        class="avatar"
        src="${isCreator ? BUILD_CONFIG.IMAGE.CREATOR_AVATAR_URL : this.iconService.api.icon.asDataUrl(ICON_IDS.user.avatarBlue, { size: 36 })}" 
        height="36" 
        width="36"
        alt="User Avatar"
        aria-hidden="true"
      >
      <a class="avatar-name" href="${data.authorUrl}" target="_blank" rel="noopener noreferrer"><span>${data.author}</span></a>
      ${isCreator || isCurrentUser
        ? `
          <img 
            class="script-creator-badge ${isCurrentUser ? BodyClasses.IS_MINE : ''}" 
            src="${isCreator ? this.iconService.api.icon.asDataUrl(ICON_IDS.role.creator, { size: 18 }) : this.iconService.api.icon.asDataUrl(ICON_IDS.role.creatorNormal, { size: 18 })}"
            height="18"
            width="18"
            title="${isCreator ? `这是 ${BUILD_CONFIG.PROJECT_NAME} 创建者` : '这是我'}"
            alt="用户标识"
            aria-hidden="true"
          >
        `
        : ''}
    </div>`)
  }

  /**
   * 添加用户类型徽章
   */
  addUserTypeBadge($element: JQuery, userTypes: GreasyForkUserType[]): void {
    // 创建徽章容器
    const $badgeContainer = $('<div class="user-badge-container"></div>').css({
      display: 'flex',
      gap: '6px',
      flexWrap: 'wrap',
      alignItems: 'center',
      margin: '4px 0',
    })

    // 批量添加徽章
    userTypes.forEach((userType) => {
      if (USER_TAG_LABELS[userType]) {
        $badgeContainer.append(`
        <div class="user-type-badge" style="
          ${getUserBadgeStyles()}
          background: ${USER_TAG_LABELS[userType].bgColor};
          color: ${USER_TAG_LABELS[userType].textColor} !important;
        ">
          <span>${USER_TAG_LABELS[userType].icon}</span>
          <span>${USER_TAG_LABELS[userType].label}</span>
        </div>
      `)
      }
    })

    // 添加到目标元素
    $element.append($badgeContainer)
  }

  getAvatarStyles(flexDirection: 'row' | 'column' = 'column'): string {
    const isRowLayout = flexDirection === 'row'

    return `
/* 头像区域 */
.${this.avatarContainerClass} {
  grid-area: avatar;
  display: flex;
  flex-direction: ${flexDirection};
  ${isRowLayout ? 'align-items: center;' : 'align-items: center; justify-content: center;'}
  gap: ${isRowLayout ? '8px' : '4px'};
  width: auto;
  max-width: none;
  margin-right: ${isRowLayout ? '0' : '30px'};
  padding: ${isRowLayout ? '16px 0' : '16px'} !important;
  width: ${isRowLayout ? 'fit-content' : '80px'}  !important;
  
  .avatar {
    border-radius: 50% !important;
  }
  
  .avatar-name {
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-align: ${isRowLayout ? 'left' : 'center'};
    font-size: 12px;
    font-weight: 500;
    padding: ${isRowLayout ? '0' : '0 8px'}; /* 添加内边距防止边缘截断 */
    z-index: 1;
    max-width: 70px !important;
    
    ${this.stylesService.link.default()}
    
    span {
      display: inline-block;
      width: fit-content;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
    }

    &:not(.${this.scriptStarClass}) {}
    
    &.${this.scriptStarClass} {
      border-radius: 8px;
      background: var(--${PROJECT_PREFIX}-theme-author-bg) !important;
      color: #2f1c0a !important;
      
      &::before {
        content: "";
        width: 16px;
        height: 16px;
        margin-right: 6px;
        background-image: var(${this.themeVarService.generateIcon(ICON_IDS.role.vipUser)}) !important;
        background-size: contain;
        flex-shrink: 0; /* 防止图标被压缩 */
      }
      
      span {
        width: calc(100% - 16px); /* 减去图标宽度 */
      }
    }
  }
}
`
  }

  isCreator(id: string): boolean {
    return this.contributorHandler.getIdsByRole(ContributorRole.Creator).includes(id)
  }
}
